package com.android.djlmapp.activity.my.zhaunchu;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.kaika.SelectNumAttestationActivity;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.dialog.MyUsualyDialog;
import com.android.djlmapp.http.GlobalUrls;
import com.android.djlmapp.listener.face.FaceResultBackListener;
import com.android.djlmapp.listener.read.SubReadDataListener;
import com.android.djlmapp.model.home.Info;
import com.android.djlmapp.tools.facetools.FaceUtils;
import com.android.djlmapp.tools.global.PrefUtils;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.kaika.SubReadCardDataUtils;
import com.android.readcard.activity.ReadCardActivity;
import com.android.readcard.bean.BackReadInfo;
import com.android.readcard.bean.CardData;
import com.android.readcard.bean.ReadCardInfo;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventCodes;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * 实名认证
 */
public class ShiMingActivity extends BaseActivity {

    @BindView(R.id.sm_smzj)
    LinearLayout smSmzj;
    @BindView(R.id.sm_name)
    TextView smName;
    @BindView(R.id.sm_num)
    TextView smNum;
    @BindView(R.id.sm_phone)
    TextView smPhone;
    @BindView(R.id.sm_get)
    TextView smGet;
    @BindView(R.id.sm_yyz)
    TextView smYyz;
    @BindView(R.id.sm_next)
    TextView smNext;
    @BindView(R.id.sm_photo)
    ImageView smPhoto;
    @BindView(R.id.sm_yzm)
    EditText smYzm;
    @BindView(R.id.ll_sm_smzj)
    LinearLayout llSmSmzj;
    @BindView(R.id.ll_sm_msg)
    LinearLayout llSmMsg;
    @BindView(R.id.top_bac)
    ImageView topBac;
    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.home_iv_readpoint)
    ImageView homeIvReadpoint;
    @BindView(R.id.top_notes)
    ImageView topNotes;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.tv_top_jump)
    TextView tvTopJump;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;
    private String idPath;
    private String filePhoto;
    private String user_name = "";
    private String user_card = "";
    private String bluetoothName = "";
    private MyUsualyDialog dialog;
    private boolean sfzSuccess = false;
    private String bd_mobile;
    private String keyvalue;
    private String mNum;

    private String sfzPhoto = "";
    private FaceUtils faceUtils;
    private Unbinder mUnbinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shi_ming);
        mUnbinder = ButterKnife.bind(this);
        initView();
        initData();
    }

    @Override
    protected void initView() {
        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.GONE);
        tvName.setText("实名认证");
    }

    @Override
    protected void onResume() {
        super.onResume();
        smNext.setEnabled(true);
        smSmzj.setEnabled(true);
    }

    @Override
    protected void initData() {
        bd_mobile = PrefUtils.getString("BD_MOBILE", "");
        dialog = new MyUsualyDialog(ShiMingActivity.this, R.layout.wait_item);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(false);

        mNum = bd_mobile.replace(bd_mobile.substring(3, 7), "****");
        smPhone.setText(mNum);
//        smPhone.setText("17699072529");
        smYzm.addTextChangedListener(phoneTextW);
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        switch (event.getCode()) {
            case EventCodes.EventReadCardCode.A: // 读卡
                smSmzj.setEnabled(true);
                dialog.show();
                BackReadInfo data = (BackReadInfo) event.getData();
                ReadCardInfo readInfo = data.getInfo();
                CardData cardData = data.getCardData();
                String chuanma = data.getChuanma();

                // 上传身份信息获取经办人数据
                SubReadCardDataUtils.getJingBanRenData(readInfo, cardData, chuanma, new SubReadDataListener() {
                    @Override
                    public void subPhotoSuc(String needJb, String photoUrl) {
                        setReadData(photoUrl, readInfo); // 处理读卡数据
                        getFacePrem(); // // 读卡成功后获取活体检测授权
                    }

                    @Override
                    public void subErr(String msg) {
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        ToastUtils.showShortToast(ShiMingActivity.this, msg);
                    }
                });
                break;
        }
    }

    /**
     * 获取活体检测授权
     */
    private void getFacePrem() {
        // 读卡成功后获取活体检测授权
        faceUtils = new FaceUtils(this,
                "0", user_name, user_card, idPath, filePhoto,
                new FaceResultBackListener() {
                    @Override
                    public void backCode(int backCode) {
                        if (backCode == 1) {
                            finish();
                        }
                    }
                });
        faceUtils.netWorkWarranty();// 取活体检测授权
    }

    /**
     * 处理读卡数据
     *
     * @param photoUrl
     * @param readInfo
     */
    private void setReadData(String photoUrl, ReadCardInfo readInfo) {
        if (dialog != null) {
            dialog.dismiss();
        }

        String idNum = readInfo.getId_num();
        String idName = readInfo.getName();

        // 身份证号中间数字星号显示
        String start = idNum.substring(0, 3);
        String end = idNum.substring(idNum.length() - 3);
        smName.setText(idName);
        smNum.setText(start + "*********" + end);

        // 加载身份证照片
        Glide.with(ShiMingActivity.this).load(photoUrl).into(smPhoto);
        sfzSuccess = true;
        PrefUtils.putString("BD_NAME", idName);
        user_card = idNum;
        user_name = idName;
        bluetoothName = readInfo.getBluetoohName();
        filePhoto = photoUrl;
        idPath = readInfo.getIdPath();


        llSmSmzj.setVisibility(View.GONE);
        llSmMsg.setVisibility(View.VISIBLE);
        smNext.setVisibility(View.VISIBLE);
    }

    TextWatcher phoneTextW = new TextWatcher() { // EditText变化监听
        private CharSequence temp;
        private int selectionStart;
        private int selectionEnd;

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            temp = s;
        }

        @Override
        public void afterTextChanged(Editable s) {
            selectionStart = smYzm.getSelectionStart();
            selectionEnd = smYzm.getSelectionEnd();
            keyvalue = smYzm.getText().toString().trim();
            //将光标移至文字末尾
            if (!TextUtils.isEmpty(keyvalue) && keyvalue.length() == 6) {
                if (temp.length() > 6) {
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionStart;
                    smYzm.setText(s);
                    smYzm.setSelection(tempSelection);
                } else {
                    dialog.show();
                    // 验证验证码
                    provingVode(keyvalue);
                }
            }
        }
    };

    private int time = 60;

    @OnClick({R.id.sm_smzj, R.id.sm_get, R.id.sm_next, R.id.ll_top_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_top_back:
                finish();
                break;
            case R.id.sm_smzj:
                smSmzj.setEnabled(false);
                // 读卡
                startActivity(new Intent(ShiMingActivity.this, ReadCardActivity.class));
                break;
            case R.id.sm_get:
                time = 60;
                smYyz.setVisibility(View.GONE);
                timeandler.sendEmptyMessage(1);
                smGet.setEnabled(false);
                dialog.show();
                getCode();
                break;
            case R.id.sm_next:
                smNext.setEnabled(false);
                if (sfzSuccess) { // 读卡成功
                    if (getYzmSuc) {

                        if (faceUtils.isShouQuan()) {
                            faceUtils.jumpActivity();
                        } else {
                            smNext.setEnabled(true);
                            // 授权失败跳转获取授权界面
                            ToastUtils.showShortToast(ShiMingActivity.this, "活体检测授权失败,请重新获取授权");
                        }

                    } else {
                        smNext.setEnabled(true);
                        ToastUtils.showShortToast(ShiMingActivity.this, "验证码未通过验证");
                    }
                } else {
                    smNext.setEnabled(true);
                    ToastUtils.showShortToast(ShiMingActivity.this, "请先扫描身份证件");
                }

                break;
        }
    }

    /**
     * 获取验证码
     */
    public void getCode() {
        MyApplication.getInstance().getHttpTools().shiMingMsgCode(GlobalUrls.GET_SMS,
                false, "", bd_mobile, new StringCallback() {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                        try {
                            parseJson(0, response.body()); // 获取验证码成功
                            dialog.dismiss();
                        } catch (Exception e) {
                            dialog.dismiss();
                            ToastUtils.showShortToast(ShiMingActivity.this, "数据解析异常");
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<String> response) {
                        super.onError(response);
                        Toast.makeText(ShiMingActivity.this,
                                "网络或服务器错误", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                });

    }

    /**
     * 验证验证码
     *
     * @param keyvalue
     */
    private void provingVode(String keyvalue) {
        MyApplication.getInstance().getHttpTools().shiMingMsgCode(GlobalUrls.SMS_CODE, true,
                keyvalue, bd_mobile, new StringCallback() {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                        try {
                            Log.i("短信验证码", "onSuccess: 验证验证码" + response.body());
                            parseJson(1, response.body());
                        } catch (Exception e) {
                            smYyz.setVisibility(View.GONE);
                            dialog.dismiss();
                            ToastUtils.showShortToast(ShiMingActivity.this, "数据解析异常");
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<String> response) {
                        super.onError(response);
                        Toast.makeText(ShiMingActivity.this,
                                "网络或服务器错误", Toast.LENGTH_SHORT).show();
                        smYyz.setVisibility(View.GONE);
                        dialog.dismiss();
                    }
                });
    }

    private boolean getYzmSuc = false;

    private void parseJson(final int index, String s) {
        Gson gson = new Gson();
        Log.i("短信验证码", "parseJson: " + s);
        Info yzmInfo = gson.fromJson(s, Info.class);
        if (yzmInfo != null) {
            getYzmSuc = true;
            if (yzmInfo.getCode() < 1000) {
                if (index == 1) { // 验证成功
                    smYyz.setVisibility(View.VISIBLE);
                    getYzmSuc = true;
                }
                dialog.dismiss();
            } else {
                if (index == 1) { // 验证
                    smYyz.setVisibility(View.GONE);
                    getYzmSuc = false;
                    dialog.show();
                    timeandler.sendEmptyMessageDelayed(0, 2000);// 提示显示两秒
                } else {
                    // 验证码获取
                    time = 0;
                    timeandler.sendEmptyMessage(1);
                    ToastUtils.showShortToast(ShiMingActivity.this, yzmInfo.msg);
                }
                dialog.dismiss();
            }
        } else {
            ToastUtils.showShortToast(ShiMingActivity.this, "服务器返回数据为空");
            dialog.dismiss();
        }
    }

    private Handler timeandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    dialog.dismiss();
                    break;
                case 1:
                    if (time > 0) {
                        smGet.setText("请" + time + "s后重试");
                        time = time - 1;
                        timeandler.sendEmptyMessageDelayed(1, 1000);
                    } else {
                        smGet.setEnabled(true);
                        smGet.setText("点击获取验证码");
                    }
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null) {
            dialog.dismiss();
        }
        mUnbinder.unbind();
    }
}
